//
//  MAPSpeedValueTool.m
//  Mars Proxy
//
//  Created by PowerfullClean on 2023/10/18.
//

#import "MAPSpeedValueTool.h"
#import <ifaddrs.h>
#import <net/if.h>
static NSUInteger const MAPYSpeedValueTime = 1;
@interface MAPSpeedValueTool()
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign, getter=isFirstTime) BOOL firstTime;
@property (nonatomic, assign) unsigned long long reData;
@property (nonatomic, assign) unsigned long long lastReData;
@property (nonatomic, assign) unsigned long long seData;
@property (nonatomic, assign) unsigned long long lastSeData;
@end
@implementation MAPSpeedValueTool
+(instancetype)mapy_toolManager{
    static dispatch_once_t onceToken;
    static MAPSpeedValueTool *tool;
    dispatch_once(&onceToken, ^{
        tool = [[self alloc] init];
        tool.firstTime = YES;
    });
    return tool;
}

-(void)dealloc{
    [_timer invalidate];
    _timer = nil;
}

- (void)mapy_startListening{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:MAPYSpeedValueTime target:self selector:@selector(mapy_getSpeedData) userInfo:nil repeats:YES];
}
- (void)mapy_stopListening{
    [self.timer invalidate];
    self.timer = nil;
}

- (void)mapy_getSpeedData{
    struct ifaddrs *addrs;
    if (getifaddrs(&addrs) == 0) {
        while (addrs != NULL) {
            struct if_data *ifa_data = (struct if_data*)addrs->ifa_data;
            if(ifa_data){
                self.reData += ifa_data->ifi_ibytes;
                self.seData += ifa_data->ifi_obytes;
            }
            addrs = addrs->ifa_next;
        }
    }
    freeifaddrs(addrs);
    
    if (!self.isFirstTime) {
        if ([self.delegate respondsToSelector:@selector(mapy_updateNetReceiveValue:)]) {
            [self.delegate mapy_updateNetReceiveValue:(self.reData - self.lastReData)/MAPYSpeedValueTime];
        }
        if ([self.delegate respondsToSelector:@selector(mapy_updateNetSendValue:)]) {
            [self.delegate mapy_updateNetSendValue:(self.seData - self.lastSeData)/MAPYSpeedValueTime];
        }
    }else{
        self.firstTime = NO;
    }
    self.lastReData = self.reData;
    self.lastSeData = self.seData;
    self.reData = 0;
    self.seData = 0;
}
@end

